import { getUserId } from '@/utils/func';

// 定义请求参数类型（支持动态覆盖默认值）
interface GetAppListParams {
    withAttention?: number; // 默认 -1
    withFlow?: number;      // 默认 1
    status?: number;      // 默认 1
}

interface UniRequestOptions {
    url: string;
    method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
    data?: any;
    header?: Record<string, string>;
    timeout?: number;
}

/**
 * 获取应用列表（带关注状态）
 * @param params 查询参数（默认 withAttention=-1，withFlow=1）
 * @returns Promise 包含接口响应数据
 */
export function getAppListWithAttention(
    params: GetAppListParams = { withAttention: -1, withFlow: 1 ,status: 1 }
): Promise<any> {
    const userId = getUserId();
    const headers: Record<string, string> = userId
        ? { 'authorization': 'Bearer '+userId }
        : {};

    const requestOptions: UniRequestOptions = {
        // 完整接口地址（若项目配置了 baseURL，可改为相对路径）
        url: 'http://192.168.0.20:3003/agentapi/agent/app/assistant/published',
        method: 'GET',
        // GET 请求的参数会自动拼接到 URL  querystring
        data: {
            withAttention: params.withAttention ?? -1,
            withFlow: params.withFlow ?? 1,
            status:params.status ?? 1
        },
        header: {
            'Content-Type': 'application/json',
            ...headers,
        },
    };

    return new Promise((resolve, reject) => {
        uni.request({
            ...requestOptions,
            success: (res) => {
                // 统一处理 HTTP 状态码
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    resolve(res.data);
                } else {
                    reject(new Error(`请求失败，状态码: ${res.statusCode}`));
                }
            },
            fail: (err) => {
                reject(err);
                setTimeout(() => {
                    uni.redirectTo({
                        url: '/pages/login/login'
                    })
                }, 1000)
            },
        });
    });
}


// ---------------------- 使用示例 ----------------------
// async function fetchAppList() {
//   try {
//     const data = await getAppListWithAttention({
//       withAttention: -1,
//       withFlow: 1,
//     });
//     console.log('应用列表数据:', data);
//     // 业务逻辑处理...
//   } catch (error) {
//     console.error('获取应用列表失败:', error);
//     uni.showToast({ title: '请求失败', icon: 'none' });
//   }
// }


// 定义接口返回的应用详情数据结构
interface AppDetail {
    createBy: string;
    createTime: string;
    updateBy: string;
    updateTime: string;
    remark: null;
    agentId: null;
    id: number;
    pid: null;
    userId: number;
    withFlow: number;
    rpaFlowId: string;
    rpaFlowIdVersion: null;
    modelId: null;
    knowledgeIds: null;
    cover: null;
    avatar: string;
    name: string;
    des: string;
    instructions: null;
    prompt: null;
    orderNumber: number;
    status: null;
    viewCount: null;
    subscribeCount: null;
    withRecommend: null;
    withTop: null;
    withHot: null;
    delFlag: string;
    categoryId: number;
    categoryName: null;
    subscribeStatus: null;
    nickName: null;
    subscribeUserId: null;
    queryType: null;
    withAttention: number;
    withRelease: number;
    permission: null;
    platforms: null;
    isTop: null;
    topTime: null;
    assistPublic: boolean;
}

// 定义会话数据结构
interface Conversation {
    id: string;
    promptId: null;
    userId: number;
    agentSign: string;
    title: string;
    createTime: string;
    username: null;
    chatTotal: null;
    tokenUsed: null;
    endTime: null;
}

// 定义props数据结构
interface Props {
    process_input_vars: null;
    process_output_vars: null;
}

// 定义完整的接口响应结构
interface ApiResponse {
    msg: string;
    code: number;
    data: AppDetail;
    conversations: Conversation[];
    conversation: Conversation;
    props: Props;
}

/**
 * 获取应用运行详情
 * @param appId 应用ID（如URL中的9）
 * @returns Promise包含接口响应数据
 */
export function getAppRunningDetail(appId: number): Promise<ApiResponse> {
    const userId = getUserId();
    const token = uni.getStorageSync('token'); // 获取存储的token

    return new Promise((resolve, reject) => {
        uni.request({
            url: `http://192.168.0.20:3003/agentapi/agent/app/runningdetail/assistant/${appId}`,
            method: 'GET',
            header: {
                'Content-Type': 'application/json',
                'x-user-id': userId || '',
                'Authorization': token ? `Bearer ${token}` : '' // 携带token
            },
            success: (res) => {
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    resolve(res.data as ApiResponse);
                } else {
                    reject(new Error(`请求失败，状态码: ${res.statusCode}`));
                }
            },
            fail: (err) => {
                reject(err);
            }
        });
    });
}


// ---------------------- 使用示例 ----------------------
// async function fetchAppDetail() {
//   try {
//     const appId = 9;
//     const data = await getAppRunningDetail(appId);

//     console.log('应用详情:', data.data);
//     console.log('会话信息:', data.conversation);

//     // 业务逻辑处理...
//     uni.showToast({ title: '获取详情成功', icon: 'success' });
//   } catch (error: any) {
//     console.error('获取应用详情失败:', error.message);
//     uni.showToast({ title: error.message || '获取详情失败', icon: 'none' });
//   }
// }

interface MessageItem {
    createBy: string;
    createTime: string;
    updateBy: string;
    updateTime: null;
    remark: null;
    id: number;
    agentId: number;
    userId: number;
    conversationId: string;
    chatId: string;
    username: null;
    role: 'user' | 'assistant';
    model: null;
    paramsMessage: string;
    message: string; // 可解析为JSON对象
    tokens: number;
    promptTokens: number;
    delFlag: string;
}

// 定义完整的接口响应结构
interface ApiResponse1 {
    code: number;
    msg: string;
    data: MessageItem[];
}

/**
 * 获取会话消息列表
 * @param conversationId 会话ID（如URL中的4f1b9642edd7da37571aef0f90c1b9df）
 * @returns Promise包含接口响应数据
 */
export function getChatMessages(conversationId: string): Promise<ApiResponse1> {
    const userId = getUserId();
    const token = uni.getStorageSync('token'); // 获取存储的token

    return new Promise((resolve, reject) => {
        uni.request({
            url: `http://192.168.0.20:3003/agentapi/agent/aigc/chat/messages/${conversationId}`,
            method: 'GET',
            header: {
                'Content-Type': 'application/json',
                'x-user-id': userId || '',
                'Authorization': token ? `Bearer ${token}` : '' // 携带token
            },
            success: (res) => {
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    resolve(res.data as ApiResponse1);
                } else {
                    reject(new Error(`请求失败，状态码: ${res.statusCode}`));
                }
            },
            fail: (err) => {
                reject(err);
            }
        });
    });
}


// ---------------------- 使用示例 ----------------------
// async function fetchChatMessagesExample() {
//   try {
//     const conversationId = '4f1b9642edd7da37571aef0f90c1b9df';
//     const data = await getChatMessages(conversationId);

//     console.log('消息列表:', data.data);

//     // 解析message字段为JSON
//     const parsedMessages = data.data.map(item => ({
//       ...item,
//       messageObj: JSON.parse(item.message)
//     }));

//     console.log('解析后的消息:', parsedMessages);

//     uni.showToast({ title: '获取消息成功', icon: 'success' });
//   } catch (error: any) {
//     console.error('获取消息失败:', error.message);
//     uni.showToast({ title: error.message || '获取消息失败', icon: 'none' });
//   }
// }

